<template>
  <div class="app-container">
    <pro-table
      ref="tableRef"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :total="total"
      @query="handleQuery"
      @add="handleAdd"
      @batch-delete="handleBatchDelete"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @refresh="getList"
    >
      <template #toolbar-left>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增员工</el-button>
      </template>
     
      <template #action="{ row }">
        <el-button type="primary" link @click="handleEdit(row)">
          <el-icon><Edit /></el-icon>编辑
        </el-button>
        <el-button type="success" link @click="handleAssignRole(row)">
          <el-icon><UserFilled /></el-icon>分配角色
        </el-button>
        <el-button type="warning" link @click="handleResetPwd(row)">
          <el-icon><Key /></el-icon>重置密码
        </el-button>
        <el-button type="danger" link @click="handleDelete(row)">
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </template>
    </pro-table>

    <!-- 用户表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="600px"
      destroy-on-close
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleAvatarChange"
              >
                <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dialogType === 'add'">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门">
              <el-tree-select
                v-model="form.deptId"
                :data="deptOptions"
                placeholder="请选择部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="500px"
    >
      <el-form :model="roleForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="roleForm.username" disabled />
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox-group v-model="roleForm.roleIds">
            <el-checkbox
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.id"
              class="role-item"
            >
              {{ role.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRoleForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

   
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, UserFilled, Key } from '@element-plus/icons-vue'  // 添加这行，导入所需图标
import ProTable from '@/components/ProTable/index.vue';

import {
  // getUserList,
  addUser,
  updateUser,
  deleteUser,
  batchDeleteUser,
  updateUserStatus,
  resetUserPassword,
  getUserRoles,
  assignUserRoles
} from '@/api'

// 列配置
const columns = [
  {
    prop: 'avatar',
    label: '头像',
    width: '80',
    align: 'center',
    hideInSearch: true,
    slot: 'avatar'
  },
  {
    prop: 'username',
    label: '用户名',
    minWidth: '120',
    search: true
  },
  {
    prop: 'nickname',
    label: '昵称',
    minWidth: '120'
  },
  {
    prop: 'deptName',
    label: '部门',
    minWidth: '120'
  },
  {
    prop: 'phone',
    label: '手机号',
    minWidth: '120',
    search: true
  },
  {
    prop: 'email',
    label: '邮箱',
    minWidth: '150'
  },
  {
    prop: 'status',
    label: '状态',
    width: '120',
    align: 'center',
    search: true,
    searchType: 'select',
    options: [
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ],
    render: 'StatusSwitch'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: '160',
    search: true,
    searchType: 'daterange'
  }
]

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const selectedRows = ref([])

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const form = ref({
  username: '',
  nickname: '',
  password: '',
  phone: '',
  email: '',
  status: 1,
  remark: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 角色相关
const roleDialogVisible = ref(false)
const roleOptions = ref([])
const roleForm = ref({
  id: null,
  username: '',
  roleIds: []
})

// 获取列表数据
const getList = async (params) => {
  loading.value = true
  try {
    // const res = await getUserList(params)
    // tableData.value = res.data.items
    // total.value = res.data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = (params) => {
  getList(params)
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    username: '',
    nickname: '',
    password: '',
    phone: '',
    email: '',
    status: 1,
    remark: ''
  }
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addUser(form.value)
          ElMessage.success('添加成功')
        } else {
          await updateUser(form.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 批量删除
const handleBatchDelete = (rows) => {
  if (!rows.length) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(
    `确认删除选中的 ${rows.length} 条数据吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const ids = rows.map(row => row.id)
      await batchDeleteUser(ids)
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
    }
  })
}

// 重置密码
const handleResetPwd = (row) => {
  ElMessageBox.confirm(
    '确认重置该用户的密码吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await resetUserPassword(row.id)
      ElMessage.success('密码重置成功')
    } catch (error) {
      console.error('密码重置失败:', error)
    }
  })
}

// 分配角色
const handleAssignRole = async (row) => {
  roleForm.value = {
    id: row.id,
    username: row.username,
    roleIds: []
  }
  try {
    const res = await getUserRoles(row.id)
    roleForm.value.roleIds = res.data.roleIds
    roleDialogVisible.value = true
  } catch (error) {
    console.error('获取用户角色失败:', error)
  }
}

// 提交角色分配
const submitRoleForm = async () => {
  try {
    await assignUserRoles({
      userId: roleForm.value.id,
      roleIds: roleForm.value.roleIds
    })
    ElMessage.success('角色分配成功')
    roleDialogVisible.value = false
  } catch (error) {
    console.error('角色分配失败:', error)
  }
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页
const handleSizeChange = (val) => {
  getList({ pageSize: val })
}

const handleCurrentChange = (val) => {
  getList({ pageNum: val })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.role-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

:deep(.el-tree-select) {
  width: 100%;
}

:deep(.el-card) {
  --el-card-padding: 16px;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.el-upload__tip {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin-top: 8px;
}

:deep(.el-button) {
  margin-left: 8px;
}

:deep(.el-icon) {
  margin-right: 4px;
}
</style> 